import { ReactNode } from "react";
import emojiNames from "@/assets/emoji/emoji-names.json";

export function transportMessageToDisplay(content: string): ReactNode[] {
  const ans: ReactNode[] = [];
  let buf: string[] = [];
  let emoji: string[] = [];
  for (let i = 0; i < content.length; ++i) {
    const c = content[i];
    if (c === "[") {
      if (emoji.length) {
        buf.push(emoji.join(""));
      }
      emoji = [c];
    } else if (c === "]") {
      if (emoji.length) {
        const emojiName = emoji.slice(1).join("");
        if (emojiNames.includes(emojiName)) {
          emoji = [];
          if (buf.length) {
            ans.push(buf.join(""));
            buf = [];
          }
          ans.push(
            <img
              key={ans.length}
              className={"xhs-emoji"}
              alt={emojiName}
              src={`/statics/assets/emoji/emoji-imgs/${emojiName}.png`}
            />,
          );
        } else {
          emoji.push(c);
          buf.push(emoji.join(""));
          emoji = [];
        }
      } else {
        buf.push(c);
      }
    } else {
      if (emoji.length) {
        emoji.push(c);
      } else {
        buf.push(c);
      }
    }
  }
  ans.push(buf.join(""));
  return ans;
}
